<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { usePlanStore } from '../stores/planStore'
import { useContainerStore } from '../stores/containerStore'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'

const router = useRouter()
const planStore = usePlanStore()
const containerStore = useContainerStore()

// 当前显示的月份
const currentMonth = ref(dayjs().startOf('month'))

// 显示创建计划对话框
const showCreateDialog = ref(false)

// 计划表单
const planForm = ref({
  title: '',
  description: '',
  category: '',
  date: dayjs().format('YYYY-MM-DD'),
  startTime: '',
  endTime: '',
  priority: 'medium',
  color: '#409EFF'
})

// 分类选项
const categoryOptions = [
  { label: '工作', value: '工作' },
  { label: '学习', value: '学习' },
  { label: '阅读', value: '阅读' },
  { label: '写作', value: '写作' },
  { label: '思考', value: '思考' },
  { label: '运动', value: '运动' },
  { label: '其他', value: '其他' }
]

// 优先级选项
const priorityOptions = [
  { label: '高', value: 'high', color: '#F56C6C' },
  { label: '中', value: 'medium', color: '#E6A23C' },
  { label: '低', value: 'low', color: '#909399' }
]

// 颜色选项
const colorOptions = [
  '#409EFF', '#67C23A', '#E6A23C', '#F56C6C', 
  '#909399', '#95d475', '#40a9ff', '#ff7875'
]

// 计算当月日历数据
const calendarData = computed(() => {
  const startOfMonth = currentMonth.value.startOf('month')
  const endOfMonth = currentMonth.value.endOf('month')
  const startOfWeek = startOfMonth.startOf('week')
  const endOfWeek = endOfMonth.endOf('week')
  
  const days = []
  let current = startOfWeek
  
  while (current.isBefore(endOfWeek) || current.isSame(endOfWeek, 'day')) {
    const dateStr = current.format('YYYY-MM-DD')
    const isCurrentMonth = current.month() === currentMonth.value.month()
    const isToday = current.isSame(dayjs(), 'day')
    const plansForDay = planStore.getPlansByDate(dateStr)
    
    days.push({
      date: current.clone(),
      dateStr,
      day: current.date(),
      isCurrentMonth,
      isToday,
      plans: plansForDay.slice(0, 3), // 最多显示3个计划
      hasMore: plansForDay.length > 3
    })
    
    current = current.add(1, 'day')
  }
  
  return days
})

// 周标题
const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']

// 切换月份
function changeMonth(offset) {
  currentMonth.value = currentMonth.value.add(offset, 'month')
}

// 创建计划
async function createPlan() {
  if (!planForm.value.title.trim()) {
    ElMessage.warning('请输入计划标题')
    return
  }
  
  try {
    await planStore.createPlan(planForm.value)
    ElMessage.success('计划创建成功')
    showCreateDialog.value = false
    resetForm()
  } catch (error) {
    ElMessage.error('创建计划失败：' + error.message)
  }
}

// 重置表单
function resetForm() {
  planForm.value = {
    title: '',
    description: '',
    category: '',
    date: dayjs().format('YYYY-MM-DD'),
    startTime: '',
    endTime: '',
    priority: 'medium',
    color: '#409EFF'
  }
}

// 点击计划
function clickPlan(plan) {
  // 确保传递数字类型的ID，匹配后端的 Long 类型
  const numericId = Number(plan.id)
  router.push({
    path: '/plan-detail',
    query: { id: numericId }
  })
}

// 点击日期
function clickDate(dayData) {
  planForm.value.date = dayData.dateStr
  showCreateDialog.value = true
}

// 获取优先级颜色
function getPriorityColor(priority) {
  const option = priorityOptions.find(opt => opt.value === priority)
  return option ? option.color : '#909399'
}

// 快速创建今日计划
function quickCreateToday() {
  planForm.value.date = dayjs().format('YYYY-MM-DD')
  showCreateDialog.value = true
}

// 组件挂载时初始化数据
onMounted(async () => {
  await planStore.initFromAPI()
  await containerStore.initFromAPI()
})
</script>

<template>
  <div class="plan-board">
    <div class="board-header">
      <h1>计划看板</h1>
      <div class="header-actions">
        <el-button type="primary" @click="quickCreateToday">
          <el-icon><Plus /></el-icon>
          今日计划
        </el-button>
      </div>
    </div>

    <!-- 月份导航 -->
    <div class="month-navigation">
      <el-button circle @click="changeMonth(-1)">
        <el-icon><ArrowLeft /></el-icon>
      </el-button>
      
      <h2 class="current-month">
        {{ currentMonth.format('YYYY年MM月') }}
      </h2>
      
      <el-button circle @click="changeMonth(1)">
        <el-icon><ArrowRight /></el-icon>
      </el-button>
    </div>

    <!-- 日历网格 -->
    <div class="calendar-container">
      <!-- 星期标题 -->
      <div class="weekdays">
        <div v-for="weekday in weekdays" :key="weekday" class="weekday">
          {{ weekday }}
        </div>
      </div>

      <!-- 日期网格 -->
      <div class="calendar-grid">
        <div 
          v-for="dayData in calendarData" 
          :key="dayData.dateStr"
          class="calendar-day" 
          :class="{
            'other-month': !dayData.isCurrentMonth,
            'today': dayData.isToday
          }"
          @click="clickDate(dayData)"
        >
          <div class="day-header">
            <span class="day-number">{{ dayData.day }}</span>
          </div>
          
          <div class="day-plans">
            <div 
              v-for="plan in dayData.plans" 
              :key="plan.id"
              class="plan-item"
              :style="{ backgroundColor: plan.color }"
              @click.stop="clickPlan(plan)"
            >
              <div class="plan-title">{{ plan.title }}</div>
              <div class="plan-time" v-if="plan.startTime">
                {{ plan.startTime }}
                <span v-if="plan.endTime">-{{ plan.endTime }}</span>
              </div>
            </div>
            
            <div v-if="dayData.hasMore" class="more-plans">
              +{{ dayData.plans.length - 3 }} 更多
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 创建计划对话框 -->
    <el-dialog
      v-model="showCreateDialog"
      title="创建计划"
      width="500px"
      @close="resetForm"
    >
      <el-form :model="planForm" label-position="top">
        <el-form-item label="计划标题" required>
          <el-input 
            v-model="planForm.title" 
            placeholder="输入计划标题"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="日期">
              <el-date-picker
                v-model="planForm.date"
                type="date"
                placeholder="选择日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="分类">
              <el-select 
                v-model="planForm.category" 
                placeholder="选择分类"
                style="width: 100%"
              >
                <el-option 
                  v-for="option in categoryOptions" 
                  :key="option.value"
                  :label="option.label" 
                  :value="option.value" 
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始时间">
              <el-time-picker
                v-model="planForm.startTime"
                format="HH:mm"
                value-format="HH:mm"
                placeholder="选择开始时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="结束时间">
              <el-time-picker
                v-model="planForm.endTime"
                format="HH:mm"
                value-format="HH:mm"
                placeholder="选择结束时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="优先级">
              <el-select 
                v-model="planForm.priority" 
                placeholder="选择优先级"
                style="width: 100%"
              >
                <el-option 
                  v-for="option in priorityOptions" 
                  :key="option.value"
                  :label="option.label" 
                  :value="option.value" 
                />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="颜色">
              <div class="color-picker">
                <div 
                  v-for="color in colorOptions"
                  :key="color"
                  class="color-option"
                  :class="{ active: planForm.color === color }"
                  :style="{ backgroundColor: color }"
                  @click="planForm.color = color"
                />
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="描述">
          <el-input 
            v-model="planForm.description"
            type="textarea"
            :rows="3"
            placeholder="计划描述（可选）"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showCreateDialog = false">取消</el-button>
          <el-button type="primary" @click="createPlan">创建</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.plan-board {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.board-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.board-header h1 {
  margin: 0;
  color: #303133;
}

.month-navigation {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 30px;
  gap: 20px;
}

.current-month {
  margin: 0;
  color: #303133;
  font-weight: 500;
  min-width: 150px;
  text-align: center;
}

.calendar-container {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.weekdays {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
}

.weekday {
  padding: 15px 10px;
  text-align: center;
  font-weight: 500;
  color: #606266;
}

.calendar-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
}

.calendar-day {
  min-height: 120px;
  border-right: 1px solid #ebeef5;
  border-bottom: 1px solid #ebeef5;
  padding: 8px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.calendar-day:hover {
  background-color: #f0f9ff;
}

.calendar-day.other-month {
  background-color: #fafafa;
  color: #c0c4cc;
}

.calendar-day.today {
  background-color: #ecf5ff;
}

.calendar-day.today .day-number {
  background-color: #409eff;
  color: white;
  border-radius: 50%;
  width: 24px;
  height: 24px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

.day-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.day-number {
  font-weight: 500;
  font-size: 14px;
}

.day-plans {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.plan-item {
  padding: 4px 8px;
  border-radius: 4px;
  color: white;
  font-size: 12px;
  cursor: pointer;
  transition: opacity 0.3s;
  position: relative;
  overflow: hidden;
}

.plan-item:hover {
  opacity: 0.8;
}

.plan-title {
  font-weight: 500;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.plan-time {
  font-size: 11px;
  opacity: 0.9;
  margin-top: 2px;
}

.more-plans {
  padding: 2px 8px;
  font-size: 11px;
  color: #909399;
  text-align: center;
  cursor: pointer;
}

.more-plans:hover {
  color: #409eff;
}

.color-picker {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.color-option {
  width: 24px;
  height: 24px;
  border-radius: 4px;
  cursor: pointer;
  border: 2px solid transparent;
  transition: all 0.3s;
}

.color-option:hover,
.color-option.active {
  border-color: #303133;
  transform: scale(1.1);
}

@media (max-width: 768px) {
  .plan-board {
    padding: 10px;
  }
  
  .board-header {
    flex-direction: column;
    gap: 15px;
    text-align: center;
  }
  
  .calendar-day {
    min-height: 80px;
    padding: 4px;
  }
  
  .plan-item {
    font-size: 10px;
    padding: 2px 4px;
  }
  
  .plan-time {
    font-size: 9px;
  }
}
</style>